#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <U8glib.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// On an arduino MEGA 2560: 20(SDA), 21(SCL)

#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3c ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32


Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);


#define X   63
#define Y   31
#define half_width  64
#define half_height 32
#define pi_1  M_PI
#define pi_2  2 * M_PI
#define pi_4  4 * M_PI
int i = 0;
int j = 0;
float x,y;
void setup() {
  Serial.begin(9600);
  if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;); // Don't proceed, loop forever
  }
  
  x_y_coordinate();
//  draw_sinx();
//  draw_cosx();
  draw_tanx();
}
void loop()
{
//  draw_sinx();
//  draw_cosx();
}

void x_y_coordinate(){  
  display.clearDisplay();
  display.drawFastHLine(0,32,SCREEN_WIDTH - 1,SSD1306_WHITE);   //垂直划线
  display.drawFastVLine(64,0,SCREEN_HEIGHT - 1,SSD1306_WHITE); //水平划线
  display.display();
}

void draw_sinx(){
  x_y_coordinate();
  dis("sin(x)");
  for(i=-half_width;i<half_width;i++)
  {
    y = (half_height-10) * sin( (pi_2/half_width)*(-i));
    x = i;
    display.drawPixel(x+X,y+Y,SSD1306_WHITE);
    display.display();
    delay(1);    
  }
  delay(2000);
  display.clearDisplay();
}

void draw_cosx(){
  x_y_coordinate();
  dis("cos(x)");
  for(i=-half_width;i<half_width;i++)
  {
    y = (half_height-10) * cos( (pi_2/half_width)*(-i));
    x = i;
    display.drawPixel(x+X,y+Y,SSD1306_WHITE);
    display.display();
    delay(1); 
  }
  delay(2000);
  display.clearDisplay();
}


void draw_tanx(){
  x_y_coordinate();
  dis("tan(x)");
  for(i=-half_width;i<half_width;i++)
  {
    y = (half_height-5) * tan( (pi_2/2/half_width)*(-i));
    x = i;
    display.drawPixel(x+X,y+Y,SSD1306_WHITE);
    display.display();
    delay(1); 
  }
  delay(2000);
  display.clearDisplay();
}
void dis(char str[])
{
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println(str);
}
